/*
 * @Date: 2021-11-30 15:42:07
 * @LastEditors: 春贰
 * @Desc: 
 * @LastEditTime: 2022-03-24 13:43:13
 * @FilePath: \web\src\composable\menu.js
 */
import { computed, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
import { findParent, findParentAll } from '@/core/tools/common'; 

export function useMenu() {

    const { getters } = useStore();
    const route = useRoute();
    const router = useRouter();
    const selectedKeys = ref([]);
    const menuStore = computed(() =>getters.routes);
    const openKeys = ref([]);
    const lastOpenKeys = ref([]);
    const layout = computed(() => getters.layout);
    const menus = ref(menuStore.value);
    

    watch(() => route.path, (path) => {
        selectedKeys.value = [path];
        let result = findParent(menus.value, path);
        openKeys.value = result;
        lastOpenKeys.value = result;
    }, { immediate: true })

    watch(() => layout.value, (layout) => {
        if(layout == "layout-comp") {
            menus.value = getters.routes.find((r) => r.path === route.matched[0].path).children;
        } else {
            menus.value = getters.routes;
        }
    })
 

    function openChange(keys) {
        const lastPath = keys.find(key => lastOpenKeys.value.indexOf(key) === -1);
        let result = findParentAll(menus.value, lastPath);
        openKeys.value = result;
        lastOpenKeys.value = result;
    }

    return {
        selectedKeys, openKeys, openChange, menus
    }
}